<?php
/**
 * 记录
 * @return
 * @author yuncran@126.com
 */

namespace app\model;

use app\BaseModel;
use app\CacheKey;

class MessageModel extends BaseModel
{

    protected $name = 'message';

    protected $pk = "msg_id";


    protected $append = ['from_user', 'to_user'];

    /**
     * 发送者
     * @param $value
     * @param $data
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author yuncran@126.com
     */
    public function getFromUserAttr($value, $data)
    {
        return UserModel::where(['id' => $data['from_user']])->field('id,nickname,avatar,email,level,bio,verification')->append(['level_name'])
            ->withAttr('level_name', function ($value, $data) {
                return UserLevelModel::where(['id' => $data['level']])->cache(CacheKey::level_title)->value('title');
            })->find();
    }

    /**
     * 接收者
     * @param $value
     * @param $data
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author yuncran@126.com
     */
    public function getToUserAttr($value, $data)
    {
        return UserModel::where(['id' => $data['to_user']])->field('id,nickname,avatar,email,level,bio,verification')->append(['level_name'])
            ->withAttr('level_name', function ($value, $data) {
                return UserLevelModel::where(['id' => $data['level']])->cache(CacheKey::level_title)->value('title');
            })->find();
    }

    public static function inData($data)
    {
        if($data['type']=='text'){

        }elseif ($data['type']=='image'){
            $data['image'] = $data['content'];
        }elseif ($data['type']=='video'){
            $data['video'] = $data['content'];
        }elseif ($data['type']=='music'){
            $data['music'] = $data['content'];
        }

        return self::getModel()->save($data);
    }


}